import { ReadOutlined, SettingOutlined, HomeOutlined, UserOutlined, BookOutlined, SafetyOutlined, HddOutlined } from '@ant-design/icons';
import { Breadcrumb, Layout, Menu, Dropdown, Avatar } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { Route, Routes, useNavigate, Link } from 'react-router-dom';
import intl from 'react-intl-universal';
import { emit } from '../locales/emit';
import HomeData from './homeData/homeData';
import Role from './role/role';
import User from './user/user';
import Knowledge from './knowledge/knowledge';
import Article from './article/article';
import Classify from './classify/classify';
import 'antd/dist/antd.min.css';
import './home.css';
import { storage, userMenu } from '../utils/localstorage';


const locales = {
    'en-US': require('../locales/en-US.json'),
    'zh-CN': require('../locales/zh-CN.json'),
};

const { Content, Sider } = Layout;

const Home = () => {
    // 初始化语言 & 切换语言
    const initLanguage = () => {
        emit.on('change_language', lang => loadLanguage(lang));         // 监听语言改变事件 'change_language'是事件标志
        loadLanguage();                                                 // 默认初始化中文
    };

    const loadLanguage = (lang = 'zh-CN') => {
        intl.init({
            currentLocale: lang,
            locales
        });
    };

    const useComponentWillMount = (cb) => {                             // 确保在组件渲染之前，先完成语言初始化
        let willMount = useRef(true);
        if (willMount.current)
            cb();
        willMount.current = false;
    };
    useComponentWillMount(initLanguage);                                // 仅在登录成功跳转到此页面时执行一次

    const [languageStyle, setLanguageStyle] = useState('zh-CN');        // state记录语言状态，初始语言是中文

    const changeLanguage = () => {                                      // 切换语言按钮 响应函数
        let val = languageStyle === 'zh-CN' ? 'en-US' : 'zh-CN';
        emit.emit('change_language', val);                              // 触发语言改变事件
        setLanguageStyle(val);
    };


    // 初始化主题 & 切换主题
    const [headerStyle, setHeaderStyle] = useState({                    // 头部状态栏，初始主题为深色
        backgroundColor: "black",
        settingStyle: <SettingOutlined className='headerSetting' />
    });
    const [siderStyle, setSiderStyle] = useState('dark');               // 左侧菜单栏
    const [borderStyle, setBorderStyle] = useState('#545454');          // 内容边框
    const [contentStyle, setContentStyle] = useState('#A8A8A8');        // 内容背景

    const changeTheme = () => {                                         // 切换主题 响应函数
        headerStyle.backgroundColor === "black" ?
            setHeaderStyle({
                backgroundColor: "white",
                settingStyle: <SettingOutlined className='headerSetting' style={{ color: 'black' }} />
            }) :
            setHeaderStyle({
                backgroundColor: "black",
                settingStyle: <SettingOutlined className='headerSetting' />
            });
        headerStyle.backgroundColor === "black" ? setSiderStyle('light') : setSiderStyle('dark');
        headerStyle.backgroundColor === "black" ? setBorderStyle('#E6FAFA') : setBorderStyle('#545454');
        headerStyle.backgroundColor === "black" ? setContentStyle('#DBDFFF') : setContentStyle('#566666');
    };


    const roleMenu = {
        'home': { key: 'sider1', icon: <HomeOutlined />, label: <Link to='/home/main'>{intl.get('home')}</Link> },
        'knowledge': { key: 'sider2', icon: <ReadOutlined />, label: <Link to='/home/knowledge'>{intl.get('knowledgeBase')}</Link> },
        'article': { key: 'sider3', icon: <BookOutlined />, label: <Link to='/home/article'>{intl.get('articleManagement')}</Link> },
        'user': { key: 'sider4', icon: <UserOutlined />, label: <Link to='/home/user'>{intl.get('userManagement')}</Link> },
        'role': { key: 'sider5', icon: <SafetyOutlined />, label: <Link to='/home/role'>{intl.get('roleManagement')}</Link> },
        'classify': { key: 'sider6', icon: <HddOutlined />, label: <Link to='/home/classify'>{intl.get('articleClassification')}</Link> },
    };


    // 左侧菜单栏数据
    const [leftMenu, setLeftMenu] = useState([]);
    useEffect(() => {
        let tempMenu = [];
        if (storage.get('user') === null || storage.get('user') ===  undefined) {
            alert(intl.get('messageOfLogin'));
            window.location.replace('/login');
        }
        storage.get('user').roles.roleMenu.map((item) => {              // 通过本地存储的用户信息获取角色菜单
            switch(item) {
                case '主页': tempMenu.push(roleMenu.home);
                            break;
                case '知识库': tempMenu.push(roleMenu.knowledge);
                            break;
                case '文章管理': tempMenu.push(roleMenu.article);
                            break;
                case '用户管理': tempMenu.push(roleMenu.user);
                            break;
                case '角色管理': tempMenu.push(roleMenu.role);
                            break;
                case '分类管理': tempMenu.push(roleMenu.classify);
                            break;
                default: break;
            }
        });
        setLeftMenu(tempMenu);
    }, [languageStyle]);


    // 退出登录
    const logout = () => {
        window.location.replace('/login');
        storage.remove('user');                                         // 移除用户信息
    };


    // 上面菜单栏
    const menu = (
        <Menu items={[{ key: '1', label: (<span onClick={changeTheme}>{intl.get('changeTheme')}</span>), },
        { key: '2', label: (<span onClick={changeLanguage}>{intl.get('changeLanguage')}</span>), },
        { key: '3', label: (<span onClick={logout}>{intl.get('logout')}</span>), },]}
        />
    );


    // 渲染组件
    return (
        <Layout>
            <div className="header" style={headerStyle}>
                <div className="logo" />
                <Avatar className='headerAvatar' style={{ backgroundColor: '#f56a00', verticalAlign: 'middle', }} size="large" gap={4}>U</Avatar>
                <Dropdown overlay={menu} placement="bottomLeft">
                    {headerStyle.settingStyle}
                </Dropdown>
            </div>
            <Layout style={{ height: '100%' }}>                         {/*解决出现竖直滚动条，而组件溢出的情况*/}
                <Sider width={200} className="site-layout-background">
                    <Menu theme={siderStyle}  items={leftMenu} mode="inline" defaultSelectedKeys={['1']} defaultOpenKeys={['sub1']} style={{height:'100%', borderRight:0,}} />
                </Sider>
                <Layout style={{ padding: '0 24px 24px', backgroundColor: borderStyle, }}>
                    <Breadcrumb style={{ margin: '16px 0' }}></Breadcrumb>
                    <Content style={{ padding: 24, margin: 0, minHeight: 280, backgroundColor: contentStyle, }}>
                        <Routes>
                            {/* 角色数量  文章大类数量  用户排行榜  文章排行榜 */}
                            <Route path='/main' element={<HomeData />} />
                            {/* <Route path='/classify' /> */}
                            {/* 知识库：浏览文章、创作文章 */}
                            <Route path='/knowledge' element={<Knowledge />} />
                            {/* 文章管理：浏览权限下的文章，创作、修改、删除文章 */}
                            <Route path='/article' element={<Article />} />
                            {/* 分类管理：查看现有分类，增删改 */}
                            <Route path='/classify' element={<Classify />} />
                            {/* 用户管理 */}
                            <Route path='/user' element={<User />} />
                            {/* 角色管理 */}
                            <Route path='/role' element={<Role />} />
                        </Routes>
                    </Content>
                </Layout>
            </Layout>
        </Layout>
    );
};

export default Home;